const Router = require('koa-router');
const mongoose = require('mongoose');
const fs = require('fs');

const categoryRouter = new Router();

categoryRouter.get('/allCategory', async (ctx) => {
  // url相对index.js文件
  await fs.readFile('./preUseFile/category.json', 'utf8', (err, data) => {
    if (err) return;
    const jsonData = JSON.parse(data);
    const Category = mongoose.model('Category');
    jsonData.RECORDS.forEach(item => {
      // 插入获取到的数据
      const newCategory = new Category(item);
      newCategory.save().then(() => {
        console.log('分类数据保存成功');
      }).catch((err) => {
        console.log(err);
      });
    });
  })
  ctx.body = '分类数据插入完成';
})

module.exports = categoryRouter;